#include "comm.hpp"

// 加载的时候构建全局变量, 会自动调用构造函数
// 程序退出的时候,析构全部变量,自动调用析构函数
Init init;

string TransToHex(key_t k)
{
    char buffer[32];
    snprintf(buffer, sizeof(buffer), "0x%x", k);
    return buffer;
}

int main()
{
    // 1.创建key
    key_t k = ftok(PATH_NAME, PROJ_ID);
    assert(k != -1);
    Log("cerate key done", Debug) << " server key : " << TransToHex(k) << endl;

    // 2.创建共享内存
    int shmid = shmget(k, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
    if (shmid == -1)
    {
        perror("shmget");
        exit(1);
    }
    Log("cerate shm done", Debug) << " shmid : " << shmid << endl;

    // 3.将共享内存,挂接到指定的地址空间
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    Log("attach shm done", Debug) << " shmid : " << shmid << endl;
    sleep(3);

    // 进行通信
    int fd = OpenFIFO(FIFO_NAME, READ); // 用管道实现共享内存的同步(达到访问控制的效果)

    for (;;)
    {
        Wait(fd);
        printf("%s\n", shmaddr);
        if (strcmp(shmaddr, "quit") == 0)
            break;
    }

    // 4.将共享内存,从自己的地址空间去关联
    int n1 = shmdt(shmaddr);
    assert(n1 != -1);

    // 5.删除共享内存
    int n2 = shmctl(shmid, IPC_RMID, nullptr);
    assert(n2!= -1);
    (void)n2;
    Log("delete shm done", Debug) << " shmid : " << shmid << endl;

    CloseFifo(fd);
    return 0;
}
